package com.sp.system.user.zuul.interceptor;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

/**
 * @author chenanhai
 * @Describle zuul 权限拦截
 * @Date 2019年12月18日
 */
@Slf4j
public class AccessUrlFilter extends ZuulFilter {

    /**
     * 不需要认证的接口
     */
    public static String antMatchers;

    @Value("${jwt.antMatchers}")
    public void setAntMatchers(String antMatchers) {
        this.antMatchers = antMatchers;
    }

    private AntPathMatcher matcher = new AntPathMatcher(System.getProperty("file.separator"));

    /**
     * pre：可以在请求被路由之前调用
     * routing： 路由请求时被调用
     * post：在routing和error过滤器之后被调用
     *
     * @return
     */
    @Override
    public String filterType() {

        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;// 优先级为0，数字越大，优先级越低
    }

    @Override
    public boolean shouldFilter() {
        return true;// 是否执行该过滤器，此处为true，说明需要过滤
    }

    @Override
    public Object run() throws ZuulException {

        log.debug("我进入第一个filter");
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        String url = request.getRequestURI();
        String[] antMatchers = AccessUrlFilter.antMatchers.split(",");
        List<String> antMatcherList = Arrays.asList(antMatchers);
        for (String antMatch : Arrays.asList(antMatchers)) {
            if (matcher.match(antMatch, url)) {
                ctx.setSendZuulResponse(true);
                ctx.setResponseStatusCode(200);
                ctx.set("isSuccess", false);
                return null;
            }
        }

        ctx.setSendZuulResponse(true);// 对该请求进行路由
        ctx.setResponseStatusCode(200);
        ctx.set("isSuccess", true);// 设值，让下一个Filter看到上一个Filter的状态

//        RequestContext context = RequestContext.getCurrentContext();
//        HttpServletRequest req = (HttpServletRequest) RequestContext.getCurrentContext().getRequest();
//        context.addZuulRequestHeader("authorization", req.getHeader("authorization"));
        return null;
    }
}
